package com.weathereport.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;

import com.weathereport.entity.Forecast;
import com.weathereport.entity.Local;

public class LocalWS {

	private Context ctx;
	private String findString;
	
	public Context getCtx() {
		return ctx;
	}

	public void setCtx(Context ctx) {
		this.ctx = ctx;
	}

	public String getFindString() {
		return findString;
	}

	public void setFindString(String findString) {
		this.findString = findString;
	}

	private HttpEntity connectWSPlaces(Context ctx, String local){
		
		HttpClient httpclient = new DefaultHttpClient();
		
        //String url =  "http://autocomplete.wunderground.com/aq?format=JSON&query=" + local;
                
		SharedPreferences settings = ctx.getSharedPreferences("prefs", ctx.MODE_PRIVATE);
        String authorization = settings.getString("authorizationPlaces", null);
		
        //Google Places API
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + local + "&types=geocode&language=pt-BR&sensor=true&key=" + authorization;
        
        HttpGet httpget = new HttpGet(url);
	    HttpResponse response;
	    HttpEntity entity = null;
	    
	    try {
	        response = httpclient.execute(httpget);
	
	        entity = response.getEntity();
	
	    } catch (ClientProtocolException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    
	    return entity;
	}
		
	public List<Local> getLocal(Context ctx, String local){
	
		HttpEntity entity = connectWSPlaces(ctx, local.replace(" ", "+"));
		
		List<Local> locals;		
		
		if (entity != null){
			
			locals = new ArrayList<Local>();
			
			// A Simple JSON Response Read
	        InputStream instream;
			try {
				instream = entity.getContent();
				String result = convertStreamToString(instream);
				instream.close();
								
				JSONObject json = new JSONObject(result);			        
		        JSONArray jsonArrayLocal = json.getJSONArray("predictions");
			    
		        if(jsonArrayLocal.length() != 0){
			        for (int i = 0; i < jsonArrayLocal.length(); i++) {
			        			        	
			        	JSONObject currentLocal = jsonArrayLocal.getJSONObject(i);
			        	
		        		Local current = new Local();
		        		current.setName(currentLocal.getString("description"));
		        		
		        		JSONArray terms = currentLocal.getJSONArray("terms");
		        		JSONArray types = currentLocal.getJSONArray("types");
			        		
		        		if (terms.length() <= 3 && types.length() == 3){
			        			
			        		if(checkTypesGeocodingWS(types, "valeu", "locality") && checkTypesGeocodingWS(types, "value", "political") &&
			        				checkTypesGeocodingWS(types, "value", "geocode")){
			        			locals.add(current);				        			
	        				}
		        		}
					}
		        }else {
		        	locals = null;
		        }
		        
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}else {
			locals = null;
		}
		return locals;		
	}
	
	private HttpEntity connectWSGeocoding(Context ctx, String local){
		
		HttpClient httpclient = new DefaultHttpClient();
                
        //Google Places API
        String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + local + "&sensor=true&language=pt-BR";
        
        HttpGet httpget = new HttpGet(url);
	    HttpResponse response;
	    HttpEntity entity = null;
	    
	    try {
	        response = httpclient.execute(httpget);
	
	        entity = response.getEntity();
	
	    } catch (ClientProtocolException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    
	    return entity;
	}
	
	public Local getCoordinates(Context ctx, String localName){
		
		HttpEntity entity = connectWSGeocoding(ctx, localName.replace(" ", "+"));
		
		Local local;
		
		if (entity != null){
			
			local = new Local();
			
			// A Simple JSON Response Read
	        InputStream instream;
			try {
				instream = entity.getContent();
				String result = convertStreamToString(instream);
				instream.close();
								
				JSONObject json = new JSONObject(result);			        
		        JSONArray jsonArrayLocal = json.getJSONArray("results");
			    
		        if(jsonArrayLocal.length() != 0){
		        	
		        	JSONObject geometry  = jsonArrayLocal.getJSONObject(0).getJSONObject("geometry");
		        	JSONObject location = geometry.getJSONObject("location");
		        				        	
	        		local.setLatitude(location.getString("lat"));
	        		local.setLongitude(location.getString("lng"));
					
		        }else {
		        	local = null;
		        }
		        
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}else {
			local = null;
		}
	
		return local;
	}
	
	private static String convertStreamToString(InputStream is) {
        		
		BufferedReader reader;
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is), 8);
			
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        return sb.toString();
    }
	
	public boolean checkTypesGeocodingWS(JSONArray jsonArray, String object, String search) throws JSONException{	
		
		boolean test = true;
		for (int j = 0; j < jsonArray.length(); j++) {
						
			if (jsonArray.get(j).equals(search)){
				
				test = true;
				j = jsonArray.length();
			}else{
				
				test = false;
			}
		}
		return test;
	}
}
